import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../data/models/sync_operation.dart';
import '../cubit/sync_bloc.dart';

class FieldOperationsTab extends StatelessWidget {
  final List<SyncOperation> operations;
  const FieldOperationsTab({super.key, required this.operations});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SyncBloc, SyncState>(
        builder:(context , state){
          var cubit = SyncBloc.get(context);
          if (operations.isEmpty) {
            return const Center(child: Text('لا يوجد عمليات فاشلة'));
          }
          return Column(
            children: [
              Expanded(
                child: ListView.builder(
                  itemCount: operations.length,
                  itemBuilder: (context, index) {
                    final operation = operations[index];
                    return BlocBuilder<SyncBloc, SyncState>(
                      buildWhen:(p,c)=> operation.operationId == state.currentLoading,
                      builder:(context ,state) {
                        return ListTile(
                          onTap: (){
                            cubit.add(ReSyncOperationEvent(operation: operation));
                          },
                          title: Text('رقم العملية: ${operation.operationId}'),
                          subtitle:(operation.errorMessage!= null)? Text('رسالة الخطأ: ${operation.errorMessage}'):null,
                          trailing:(state.currentLoading != operation.operationId)? const Icon(Icons.error, color: Colors.red):const CircularProgressIndicator(color: Colors.orange,),
                        );
                      },
                    );
                  },
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: ElevatedButton(
                  onPressed: () {
                    cubit.add(SyncPendingOperationsEvent());
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor:Colors.green,
                    foregroundColor: Colors.white,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(Icons.refresh,color: Colors.black,),
                        Text(
                          'إعادة محاولة',
                          style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: Colors.black),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          );
        }
    );
  }
}
